package com.wbj.direction.sensor.direction

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.wbj.direction.sensor.BaseSensorView
import com.noboauto.vehicle.view.util.AltitudeUtil
import com.wbj.direction.Constant
import com.wbj.direction.R
import kotlin.math.abs

/**
 * @auth: WANGCHUANGJUN
 * @mail: 910868438@qq.com
 * @desc:
 * @date: 2021/12/13 16:22
 */
open class DirectionView : BaseSensorView {

    override val TAG = this::class.java.simpleName
    var currentDegree = 0f
    var currentDegreeShow = 0f
    val itemWidth = context.resources.getDimensionPixelOffset(R.dimen.direction_item_view_width)
    lateinit var recyclerView: ShadowRecyclerView
    val list: ArrayList<Int> = ArrayList();
    var mWidth: Int = 150
    var mHeight: Int = 50
    val dropDownDrawable: Drawable =
        context.resources.getDrawable(R.drawable.drop_down, context.theme)
    lateinit var layoutManager: LooperLayoutManager
    var lastUpdateTime: Long = 0;
    lateinit var adapter: DirectionAdapter

    var directStr = "南";
    val mPaint: Paint by lazy { Paint(Paint.ANTI_ALIAS_FLAG) }
    var isNeedParentDraw = true

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        initView()
    }

    open fun initView() {
        val param = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        recyclerView = ShadowRecyclerView(context)
        recyclerView.layoutParams = param
        layoutManager = LooperLayoutManager(context)
        layoutManager.looperEnable = true
        recyclerView.layoutManager = layoutManager

        for (angle in 0..345 step 15) {
            list.add(angle)
        }
        adapter = DirectionAdapter(list, context)
        recyclerView.adapter = adapter
        addView(recyclerView)


        mPaint.color = Color.parseColor("#419C3A")
        mPaint.isAntiAlias = true
        mPaint.textSize = AltitudeUtil.sp2px(context, 21f).toFloat()

    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        return true
    }

    override fun onSensorChanged(event: SensorEvent?) {
        if (System.currentTimeMillis() - lastUpdateTime < 200) return

        lastUpdateTime = System.currentTimeMillis()
        var sensorType = event?.sensor?.type
        if (sensorType == Sensor.TYPE_ORIENTATION) {
            var degree = event?.values?.get(0)?.minus((mWidth-itemWidth)*15/itemWidth/2)
            Log.i(TAG, "onSensorChanged:currentDegree: ${currentDegree},degree:${event?.values?.get(0)}")
            if (degree != null && abs((degree - currentDegree)) >= 1) {
                when {
                    degree - currentDegree > 180 -> {
                        recyclerView.smoothScrollBy((((degree - 360 - currentDegree) / 15f) * itemWidth ).toInt(),
                            0)
                    }
                    currentDegree - degree > 180 -> {
                        recyclerView.smoothScrollBy((((degree + 360 - currentDegree) / 15f) * itemWidth).toInt(),
                            0)
                    }
                    else -> {
                        recyclerView.smoothScrollBy((((degree - currentDegree) / 15f) * itemWidth).toInt(),
                            0)
                    }
                }
                currentDegree = degree
                currentDegreeShow = event?.values?.get(0)!!
                invalidate()
                postInvalidate()
            }
        }
    }

    override fun onAccuracyChanged(p0: Sensor?, p1: Int) {

    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val wSize = MeasureSpec.getSize(widthMeasureSpec)
        val hSize = MeasureSpec.getSize(heightMeasureSpec)
        if (mWidth <= wSize) {
            mWidth = wSize
        }
        if (mHeight <= hSize) {
            mHeight = hSize
        }
        setMeasuredDimension(mWidth, mHeight)
    }

    override fun dispatchDraw(canvas: Canvas) {
        super.dispatchDraw(canvas)
        if (!isNeedParentDraw)return
        when (currentDegreeShow) {
            in 0.0..22.0    -> directStr = "北"
            in 338.0..360.0 -> directStr = "北"
            in 23.0..67.0   -> directStr = "东北"
            in 68.0..112.0  -> directStr = "东"
            in 113.0..157.0 -> directStr = "东南"
            in 158.0..202.0 -> directStr = "南"
            in 203.0..247.0 -> directStr = "西南"
            in 248.0..292.0 -> directStr = "西"
            in 293.0..337.0 -> directStr = "西北"
        }
        mPaint.color = Color.BLACK
        canvas.drawRect((mWidth - mPaint.measureText("东北")) / 2f,
            0f,
            (mWidth + mPaint.measureText("东北")) / 2f,
            itemWidth.toFloat(),
            mPaint)
        dropDownDrawable.setBounds((mWidth - itemWidth) / 2,
            0,
            (mWidth + itemWidth) / 2,
            itemWidth / 2)
        dropDownDrawable.draw(canvas)
        mPaint.color = Color.parseColor("#419C3A")
        canvas.drawText(directStr,
            (mWidth - mPaint.measureText(directStr)) / 2f,
            itemWidth * 3 / 4f,
            mPaint)
    }
}